<template>
  <div>
    <div>

      <el-row>
        <el-col :span=20 :offset="2" style="margin-bottom: 30px">

          <el-menu mode="horizontal">
            <el-menu-item>
              <el-button @click="chooseClassVisible=true">选择管理的教学班</el-button>
            </el-menu-item>
            <el-menu-item v-if="isHwListReady">
              已选择的教学班 : {{
                chosenClass.course_name + ' ' +
                chosenClass.year + ' ' +
                chosenClass.semester + ' ' +
                chosenClass.schedule
              }}

            </el-menu-item>
            <el-menu-item style="float: right" v-if="inCorrect" @click="inCorrect=false">
              返回作业管理
            </el-menu-item>
          </el-menu>
        </el-col>

        <el-col :span="22" :offset="1" v-if="isHwListReady&&!inCorrect">

          <el-tabs v-model="chosenOp" tab-position="right" @tab-click="switchTabs">
            <el-tab-pane label="查看与批改作业" name="查看与批改作业">
              <el-table
                stripe
                :data="hwList"
                style="width: 100%">
                <el-table-column type="expand" fixed="left">
                  <template slot-scope="props">
                    <el-form label-position="left">
                      <el-form-item label="作业描述：">
                        <span>{{ props.row.assignmentDescription }}</span>
                      </el-form-item>
                      <!--                      <el-form-item label="Tips：">-->
                      <!--                        <span>到课件列表中去</span>-->
                      <!--                      </el-form-item>-->
                    </el-form>
                  </template>
                </el-table-column>
                <el-table-column sortable label="作业名称" width="180" fixed="left">
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" content="展开行以查看详情" placement="top-start">
                      <b>
                        {{ scope.row.assignmentName }}
                      </b>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="发布与截止日期" width="250">
                  <template slot-scope="scope">
                    <div style="margin: 5px">
                      <el-tag size="mini" type="success">起</el-tag>
                      {{ $global.formatTimeString(scope.row.startTime) }}
                    </div>
                    <div style="margin: 5px">
                      <el-tag size="mini" type="danger">止</el-tag>
                      {{ $global.formatTimeString(scope.row.endTime) }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column sortable label="上交情况">
                  <template slot-scope="scope">
                    {{ 100 - stuList.length }}/{{ stuList.length }}
                  </template>
                </el-table-column>


                <el-table-column label="操作" fixed="right" width="220">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="editHw(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                      size="mini"
                      @click="correctHw(scope.$index, scope.row)">批改
                    </el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="delHw(scope.$index, scope.row)">删除
                    </el-button>

                  </template>
                </el-table-column>

              </el-table>

            </el-tab-pane>


            <el-tab-pane label="添加作业" name="添加作业">
              <el-form :model="hwForm" ref="hwForm" label-width="150px" class="demo-ruleForm">
                <el-form-item label="作业名称" required prop="assignmentName">
                  <el-input type="text" v-model="hwForm.assignmentName"></el-input>
                </el-form-item>
                <el-form-item label="作业描述" required prop="assignmentDescription">
                  <el-input v-model="hwForm.assignmentDescription" placeholder="请输入课件描述"
                            type="textarea" :rows="4"></el-input>
                </el-form-item>
                <el-form-item label="开始日期时间" required prop="startTime">
                  <el-date-picker
                    v-model="hwForm.startTime"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="截止日期时间" required prop="endTime">
                  <el-date-picker
                    v-model="hwForm.endTime"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>


                <el-form-item>
                  <el-button type="primary" @click="submitHwForm('hwForm')">
                    {{ isUpdate ? '更新作业' : '创建新作业' }}
                  </el-button>
                  <el-button @click="resetForm('hwForm')">
                    {{ isUpdate ? '更改模式为创建新作业' : '重置内容' }}
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

          </el-tabs>
        </el-col>
      </el-row>
    </div>
    <div>
      <CorrectingHw v-if="inCorrect" :chosenClass="chosenClass" :chosenAssignmentId="chosenAssignmentId"> </CorrectingHw>
    </div>

    <div class="dialogSection">
      <el-dialog
        title="选择管理的教学班"
        :visible.sync="chooseClassVisible"
        width="30%"
        center
        destroy-on-close
      >
        <el-select v-model="chosenClass" placeholder="请选择要管理的课程" @change="handleCourseChange">
          <el-option
            v-for="item in classes"
            :key="item.course_name"
            :label="item.course_name+' '+item.year+' '+item.semester+' '+item.schedule"
            :value="item">
          </el-option>
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelChoose">取 消</el-button>
          <!--          <el-button type="primary" @click="confirmChooseClass">确 定</el-button>-->
        </div>
      </el-dialog>
    </div>


  </div>
</template>

<script>
import tc from "../../store/teacher"
import axios from 'axios'
import qs from 'qs'
import CorrectingHw from "./utilComp/CorrectingHw";

export default {
  name: "HWManage",
  components: {CorrectingHw},
  computed: {
    classes() {
      return tc.getters.getClasses
    },
    stuList: {
      get() {
        return tc.getters.getStuList
      },
      set(v) {
        tc.commit('setStuList', v)
      },
    }

  },
  mounted() {

  },
  data() {
    return {

      chosenClass: null,
      chooseClassVisible: false,
      isHwListReady: false,
      chosenAssignmentId:0,
      chosenOp: '查看与批改作业',
      isUpdate: false,// 是否是修改而非新增作业条目
      hwList: [
        {
          // courseId: 10086,
          // assignmentId: 1,
          // assignmentName: '作业1',
          // startTime: '日期1',
          // endTime: '日期2',
          // assignmentDescription: 'Lorem ipsum dolor sit amet'
        },

      ],

      hwForm: {
        courseId: 10086,
        assignmentName: '',
        assignmentDescription: '',
        startTime: null,
        endTime: null,
      },
      inCorrect: false,

    }
  },
  methods: {
    /**
     * 选择课程时，读取对应课程的数据
     * @param chosen value
     */
    async handleCourseChange(chosen) {
      axios.post('/api/showAllAssignmentTopics', qs.stringify({courseId: chosen.courseId}))
        .then(res1 => {
          this.hwList = res1.data.assignmentTopicList
          this.chooseClassVisible = false
          this.isHwListReady = true
          console.log(res1)
        })
      axios.post('/api/getStudentsByClassId', qs.stringify({courseId: this.chosenClass.courseId}))
        .then(res1 => {
          console.log(res1, '学生列表')
          this.stuList = res1.data.studentsList
        })


    },
    switchTabs(tab, event) {
      if (!this.isUpdate) {
        this.$refs['hwForm'].resetFields();
      }
    },
    editHw(index, row) {
      console.log(index, row);
      this.isUpdate = true
      this.hwForm = row
      // 复制courseId
      this.chosenOp = '添加作业'

    },
    correctHw(index, row) {
      // console.log(index, row);
      this.chosenAssignmentId=row.assignmentId
      this.inCorrect = true
    },
    delHw(index, row) {
      axios.post('/api/deleteAssignmentTopic', qs.stringify({courseId: row.courseId, assignmentId: row.assignmentId}))
        .then(res1 => {
          console.log(res1)
          this.hwList.splice(index, 1)
          this.$message.success('删除成功')
        })
      // console.log(index, row);
    },

    submitHwForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.hwForm.courseId = this.chosenClass.courseId
          if (this.isUpdate) {// 更新表单
            // this.hwForm.assignmentId = this.hwList.length

            // 需要把后端传来的时间重新转换成标准化时间
            this.hwForm.startTime = Date(Date.parse(this.hwForm.startTime)).toString()
            this.hwForm.endTime = Date(Date.parse(this.hwForm.endTime)).toString()
            axios.post('/api/modifyAssignmentTopic', qs.stringify(this.hwForm)).then(res1 => {
              console.log(res1)
              this.$message.success('修改作业项成功')
            }).catch(err1 => {
              console.log(err1, '更新失败', this.hwForm)
            })
          } else {
            // 将新的作业项插入,必须把时间转化成字符串
            this.hwForm.startTime = this.hwForm.startTime.toString()
            this.hwForm.endTime = this.hwForm.endTime.toString()
            axios.post('/api/createAssignmentTopic', qs.stringify(this.hwForm)).then(res1 => {
              console.log(res1)
              // 本来插入应当放这里
              this.hwForm.assignmentId = res1.data.assignmentId
              this.hwList.push(this.hwForm)
              this.$message.success('新建作业项成功')
            }).catch(err1 => {
              console.log(err1, '上传后端失败')
              console.log(this.hwForm)
            })

          }
          this.hwForm = {} // 重设表单
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      console.log(this.hwForm)
      if (this.isUpdate) {
        this.hwForm = {}
        this.isUpdate = false// 变为新建模式
      } else {
        this.$refs[formName].resetFields();
      }

    },

    /**
     * 确定选择课程。通过请求读取到作业列表后再展示
     */
    // confirmChooseClass() {
    //
    //
    // },
    cancelChoose() {
      this.chooseClassVisible = false
    }


  },

}
</script>

<style scoped>
.hwman_main {
  text-align: center;
}

</style>
